package com.geek.novel.services

import android.content.res.Resources
import android.text.TextUtils
import com.geek.novel.R
import com.geek.novel.bo.AppContext
import com.geek.novel.entity.BookRead
import com.geek.novel.utils.ToastUtils
import com.vicpin.krealmextensions.delete
import com.vicpin.krealmextensions.query
import com.vicpin.krealmextensions.queryFirst
import com.vicpin.krealmextensions.save
import io.realm.Sort

class BookRepository private constructor(){

	private val bookIndexRepository = BookIndexRepository()
	private val bookSectionRepository = BookSectionRepository()

	/**单例模式*/
	companion object{
		@Volatile
		private var instance: BookRepository? = null
		fun getInstance(): BookRepository {
			if(instance == null){
				synchronized(BookRepository::class.java){
					if(instance == null){
						instance = BookRepository()
					}
				}
			}
			return instance!!
		}
	}

	private fun getResources(): Resources {
		return AppContext.getResources()
	}
	
	/**获取我的书架所有书籍*/
	fun findAllBookshelf(): List<BookRead>{
		return BookRead().query { equalTo("collect", true) }
	}
	
	/**根据书本id获取章节*/
	fun findBookByBookId(bookId: String?): BookRead?{
		if(TextUtils.isEmpty(bookId)){
			return null
		}
		return BookRead().queryFirst { equalTo("bookId", bookId) }
	}

	/**根据书本名称获取章节*/
	fun findBookByName(name: String?): BookRead?{
		if(name == null || name.trim() == ""){
			throw RuntimeException(getResources().getString(R.string.prompt_read_section_error))
		}
		return BookRead().queryFirst { equalTo("name", name) }
	}

	/**获取最大的排序号*/
	private fun getMaxSort(): BookRead?{
		return BookRead().queryFirst { sort("sort", Sort.DESCENDING) }
	}

	/**排序书籍*/
	private fun setBookToTop(book: BookRead){
		//设置排序号
		val maxSortBook = getMaxSort()
		if(maxSortBook != null && maxSortBook.sort!=0 && book.sort == maxSortBook.sort){
			return
		}
		val sort = if(maxSortBook != null){
			maxSortBook.sort + 1
		}else{
			1
		}
		book.sort = sort
	}

	/**保存*/
	fun save(book: BookRead){
		book.save()
	}
	
	/**排序书籍并保存*/
	fun saveBookToTop(book: BookRead){
		this.setBookToTop(book)
		save(book)
	}

	/**删除书籍*/
	fun deleteBook(book: BookRead){
		//本地书籍要删除章节和索引信息，其他书籍到时专门有个清除缓存的入口
		if(book.local){
			//删除章节信息
			bookSectionRepository.deleteByBookId(book.bookId!!)
			//删除索引信息
			bookIndexRepository.deleteByBookId(book.bookId!!)
		}
		//删除实体信息
		book.delete { equalTo("id", book.id) }
	}



	/**加入书架或者移除书架功能*/
	fun toggleBookshelf(book: BookRead?){
		if(book == null){
			ToastUtils.toast("数据未加载完成，请稍候")
			return
		}
		var bookDb = this.findBookByBookId(book.bookId)
		if(bookDb == null){
			bookDb = book
		}
		bookDb.collect = !bookDb.collect
		book.collect = bookDb.collect
		//保存书架，并挪到最顶部
		this.saveBookToTop(bookDb)
	}

}